package com.botarena.server.servlets.http;

import java.util.logging.Logger;
import java.io.IOException;

import javax.jdo.PersistenceManager;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.botarena.server.dao.BattleProcessDAO;
import com.botarena.server.dao.helper.NonTransactional;
import com.botarena.server.model.BattleProcess;
import com.botarena.server.services.DAOService;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

public class TestServlet extends HttpServlet {

	private static final long serialVersionUID = -8740874056951827002L;
	
	private static final Logger log = Logger.getLogger(TestServlet.class.getName());
	
	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		final Key k = KeyFactory.createKey(BattleProcess.class.getSimpleName(), 987654321);
		
		DAOService.execute(new NonTransactional() {

			@Override
			public void doOutsideTransaction(PersistenceManager pm) {
				BattleProcessDAO dao = new BattleProcessDAO(pm);
				
				BattleProcess p = new BattleProcess();
				p.setKey(k);
				p.addMove(1);
				p.addMove(2);
				p.addMove(3);
				dao.create(p);
				
			}
			
		});
		
		DAOService.execute(new NonTransactional() {

			@Override
			public void doOutsideTransaction(PersistenceManager pm) {
				BattleProcessDAO dao = new BattleProcessDAO(pm);
				
				BattleProcess p = dao.getByKey(k);
				int s = p.getMoves().size();
				
				log.info("Collection size: " + s + " (should be 3)");
				
			}
			
		});
		
		response.getOutputStream().write("plum!".getBytes());
		response.getOutputStream().close();
		
	}
}
